<script lang="ts" setup>
import { createPoleAPI, delPoleAPI, getAreaDropListAPI, getPoleListAPI, updatePoleAPI } from '@/apis/pole';
import type { AreaDropListData, Pole, PoleListParams, PoleParams } from '@/types/pole';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref } from 'vue';

const list = ref<Pole[]>([])
const total = ref(0)
const params = ref<PoleListParams>({
  page: 1,
  pageSize: 10,
  poleName: '',
  poleNumber: '',
  poleStatus: ''
})
const getList = async () => {
  const res = await getPoleListAPI(params.value)
  console.log('list',res)
  list.value = res.data.rows
  total.value = res.data.total
}

getList()
const onSearch = () => {
  params.value.page = 1
  getList()
}

// 弹窗部分
const areaList = ref<AreaDropListData[]>([])
const getAreaList = async () => {
  const res = await getAreaDropListAPI()
  console.log('drop',res)
  areaList.value = res.data
}
const visible = ref(false)
const confirmLoading = ref(false)
const onClose = () => {
  visible.value = false
  // 重置表单数据
  addForm.value = initAddForm()
  addFormRef.value?.resetFields()
  visible.value = false
}

getAreaList()
const onOpen = () => {
  visible.value = true
}
const onEdit = (row: Pole) => {
  console.log('row',row)
  visible.value = true
  addForm.value = {
    poleName: row.poleName,
    poleNumber: row.poleNumber,
    poleIp: row.poleIp,
    areaId: row.areaId,
    poleType: row.poleType,
    id: row.id
  }
}
const onSubmit = async () => {
  try {
    // 表单校验
    await addFormRef.value?.validate()
    confirmLoading.value = true

    if(addForm.value.id){
      await updatePoleAPI(addForm.value)
      ElMessage.success('修改成功')
    }else{
      await createPoleAPI(addForm.value)
     ElMessage.success('添加成功')
    }

    getList()
    onClose()
    confirmLoading.value = false
  }catch{
    confirmLoading.value = false
  }
}
const initAddForm = () => {
  return {
  poleName: '',
  poleNumber: '',
  poleIp: '',
  areaId: undefined,
  poleType: 'entrance'  as 'entrance' | 'export'
}
}
const addForm = ref<PoleParams>(initAddForm())
const addFormRef = ref<FormInstance>()
const addFormRules = ref<FormRules<PoleParams>>({
  poleName: [
    { required: true, message: '请输入一体杆名称', trigger: 'blur' }
  ],
  poleNumber: [
    { required: true, message: '请输入一体杆编号', trigger: 'blur' }
  ],
  poleIp: [
    { required: true, message: '请输入一体杆IP', trigger: 'blur' },
    { pattern: /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/, message: '请输入正确的IP地址', trigger: 'blur' }
  ],
  areaId: [
    { required: true, message: '请选择安装区域', trigger: 'change' }
  ],
  poleType: [
    { required: true, message: '请选择一体杆类型', trigger: 'change' }
  ]
})

const selectionCardList = ref<Pole[]>([])
const onSelectionChange = (val: Pole[]) => {
  console.log('selection',val)
  selectionCardList.value = val
}
const onDel = async (ids: number[]) => {
// 如果没有选择数据，则轻提示
if(ids.length === 0 ) return ElMessage.warning('请选择要删除的一体杆')
    ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(async() => {
      await delPoleAPI(ids)
      ElMessage.success('删除成功')
      getList()
    }).catch(() => {})
  
}

</script>

<template>
  <div class="card-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <span class="search-label">一体杆名称：</span>
      <el-input clearable v-model="params.poleName" placeholder="请输入一体杆名称" class="search-main" />
      <span class="search-label">一体杆编号：</span>
      <el-input clearable v-model="params.poleNumber" placeholder="请输入一体杆编号" class="search-main" />
      <span class="search-label">运行状态：</span>
      <el-select style="width: 240px" v-model="params.poleStatus" placeholder="全部" clearable>
        <el-option label="正常" value="0" />
        <el-option label="异常" value="1" />
      </el-select>
      <el-button type="primary" class="search-btn" @click="onSearch">查询</el-button>
    </div>
    <!-- 新增删除操作区域 -->
    <div class="create-container">
      <el-button type="primary" @click="onOpen">添加一体杆</el-button>
      <el-button @click="onDel(selectionCardList.map(item => item.id ))">批量删除</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table @selection-change="onSelectionChange" style="width: 100%" :data="list">
        <el-table-column type="selection"  width="50" />
        <el-table-column type="index" label="序号" width="100" />
        <el-table-column prop="poleName" label="一体杆名称" />
        <el-table-column prop="poleNumber" label="一体杆编号" />
        <el-table-column prop="poleIp" label="一体杆IP" />
        <el-table-column prop="areaName" label="安装区域" />
        <el-table-column prop="poleType" label="一体杆类型">
          <template #default="{ row }">
            {{ row.poleType === 'center' ? '中心' : row.poleType === 'entrance' ? '入口' : '出口' }}
          </template>
        </el-table-column>
        <el-table-column prop="poleStatus" label="运行状态">
          <template #default="{ row }">
            <el-tag v-if="row.poleStatus === 0" type="success">正常</el-tag>
            <el-tag v-else type="danger">异常</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="onEdit(row)">编辑</el-button>
            <el-button size="small" type="primary" link @click="onDel([row.id])">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="page-container">
      <el-pagination 
      layout="total, prev, pager, next, sizes, jumper" 
      :total="total" 
      v-model:current-page="params.page" 
      v-model:page-size="params.pageSize"
      @change="getList()"
      />
    </div>
    <el-dialog :title="addForm.id ? '编辑一体杆' : '添加一体杆'" width="600px" v-model="visible" @close="onClose">
      <!-- <span>这事一个消息</span> -->
       <div class="form-container">
        {{ addForm }}
        <el-form label-position="top" :model="addForm" :rules="addFormRules" ref="addFormRef">
          <el-form-item label="一体杆名称：" prop="poleName">
            <el-input v-model="addForm.poleName" placeholder="请输入一体杆名称" />
          </el-form-item>
          <el-form-item label="一体杆编号：" prop="poleNumber">
            <el-input :disabled="addForm.id ? true : false" v-model="addForm.poleNumber" placeholder="请输入一体杆编号" />
          </el-form-item>
          <el-form-item label="一体杆IP：" prop="poleIp">
            <el-input v-model="addForm.poleIp" placeholder="请输入一体杆IP" />
          </el-form-item>
          <el-form-item label="安装区域：" prop="areaId">
            <el-select  v-model="addForm.areaId" placeholder="请选择安装区域" clearable>
              <el-option v-for="item in areaList" :key="item.areaId" :label="item.areaName" :value="item.areaId" />
            </el-select>
          </el-form-item>
          <el-form-item label="一体杆类型：" prop="poleType">
            <el-select  v-model="addForm.poleType" placeholder="请选择一体杆类型" clearable>
              <el-option label="入口" value="entrance" />
              <el-option label="出口" value="export" />
            </el-select>
          </el-form-item>
        </el-form>
       </div>
      <template #footer>
        <div class="dialog-footer">
           <el-button size="small" @click="onClose">取 消</el-button>
           <el-button size="small" type="primary" @click="onSubmit" :loading="confirmLoading">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.card-container {
  padding: 20px;
  background-color: #fff;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  padding-bottom: 20px;

  .search-main {
    width: 220px;
    margin-right: 10px;
  }

  .search-btn {
    margin-left: 20px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>